import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {setToken, setUserInfo, UserInfo} from '@utils/auth';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '@app/services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;

  submitForm(): void {
    for (const key of Object.keys(this.validateForm.controls)) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      console.log(this.validateForm.value);
      this.authService.login(this.validateForm.value).subscribe(
        (data) => {
          console.log(data);
          if (data.code === 200) {
            setToken(data.data);
            const userInfo = new UserInfo(this.validateForm.value.email);
            setUserInfo(userInfo);
            this.router.navigateByUrl('/home');
          } else if (data.code === 403) {
            console.log(data.msg);
          }
        },
        (error) => {
          console.log(error);
        }
      );
    }
  }

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private $http: HttpClient,
    private authService: AuthService
  ) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      email: [null, [Validators.required, Validators.email]],
      password: [null, [Validators.required]],
      rememberme: [true],
    });
  }
}
